package com.bndg.blackjack

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.map

class GameViewModel : ViewModel() {
    private val _gameState = MutableLiveData<GameState>().apply {
        value = GameState()
    }
    val gameState: LiveData<GameState> get() = _gameState
    // 显示庄家操作面板
    val showDealerControl: LiveData<Boolean> = gameState.map { state ->
        MsgManager.myId.equals(state.dealerId)
    }

    // 显示玩家操作面板
    val showPlayerControl: LiveData<Boolean> = gameState.map { state ->
        MsgManager.myId.equals(state.playerId)
    }

    // 邀请按钮是否可用
    val enableInviteButton: LiveData<Boolean> = gameState.map { state ->
        // 没有玩家 || 玩家未接受邀请 ||  玩家离开
        state.playerId.isEmpty() || !state.isPlayerAccepted || state.isPlayerLeft
    }

    // 开始一局按钮是否可用
    val enableStartButton: LiveData<Boolean> = gameState.map { state ->
        // 玩家已接受邀请 && 玩家未离开 && 当前对局未结束 && 当前筹码 > 0
        state.isPlayerAccepted && !state.isPlayerLeft && !state.isPlaying && state.currentChips > 0
    }

    // 玩家按钮是否可用
    val enablePlayerButton: LiveData<Boolean> = gameState.map { state ->
        // 玩家手牌非空 && 在对局中 && 当前是玩家回合
        state.playerCards?.isNotEmpty() == true
                && state.isPlaying
                && state.currentTurn == Turn.PLAYER
    }

    // 筹码布局是否可用
    val enableChipLayout: LiveData<Boolean> = gameState.map { state ->
        // 玩家总筹码 > 0 && 当前对局未开始 && 是玩家 && 当前是玩家回合
        state.playerChips > 0 && !state.isPlaying
                && MsgManager.myId.equals(state.playerId)
                && state.currentTurn == Turn.PLAYER
    }

    // 更新游戏状态的方法
    fun updateGameState(newState: GameState) {
        _gameState.value = newState
    }
}